﻿using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;

using Moe.ECamel.Common.Entities;

namespace Moe.ECamel.Server.BL
{
	public class RentalBL : ECamelBL
	{
		public RentalBL(ECamelDataContext dataContext)
			: base(dataContext)
		{
		}

		public List<Rental> GetCustomerActiveRentals(int customerId)
		{
			// Configure load options:
			DataLoadOptions loadOptions = new DataLoadOptions();
			loadOptions.LoadWith<Rental>(r => r.Inventory);
			loadOptions.LoadWith<Inventory>(i => i.Item);
			loadOptions.LoadWith<Item>(i => i.ItemType);
			ECamelDataContext adhocDC = new ECamelDataContext(dataContext.Connection);
			adhocDC.ObjectTrackingEnabled = false;
			adhocDC.LoadOptions = loadOptions;

			var rentals = from r in adhocDC.Rentals
						  where r.CustomerId == customerId && r.Active
						  orderby r.RentalDate descending 
						  select r;

			return rentals.ToList();
		}
		public List<Rental> GetCustomerRentals(int customerId)
		{
			// Configure load options:
			DataLoadOptions loadOptions = new DataLoadOptions();
			loadOptions.LoadWith<Rental>(r => r.Inventory);
			loadOptions.LoadWith<Inventory>(i => i.Item);
			loadOptions.LoadWith<Item>(i => i.ItemType);
			ECamelDataContext adhocDC = new ECamelDataContext(dataContext.Connection);
			adhocDC.ObjectTrackingEnabled = false;
			adhocDC.LoadOptions = loadOptions;

			var rentals = from r in adhocDC.Rentals
						  where r.CustomerId == customerId
						  orderby r.RentalDate descending
						  select r;

			return rentals.ToList();
		}

		public void RentItem(Rental rental)
		{
			this.dataContext.Rentals.InsertOnSubmit(rental);
		}

		public int GetActiveRentalsByCustomerAndItemType(int customerId, int itemTypeId)
		{
			var query = from r in dataContext.Rentals
			            where r.CustomerId == customerId && r.Active && r.Inventory.Item.ItemTypeId == itemTypeId
			            select r;

			return query.Count();
		}

		public Rental GetRentalById(int rentalId)
		{
			return dataContext.Rentals.Single(r => r.RentalId == rentalId);
		}

		public IList<Rental> GetOverdueRentals(DateTime date)
		{
			return (from r in dataContext.Rentals
			        where r.ActualReturnDate == null && r.ExpectedReturnDate <= date && r.OverdueMailMessageId == null
			        select r).ToList();
		}
	}
}